package com.haipumi.actions;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.haipumi.beans.JsonModel;
import com.haipumi.beans.haipumi_customerService;
import com.haipumi.biz.CustomerServiceBiz;
import com.haipumi.utils.CommonData;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerServiceAction extends ActionSupport {

	private static final long serialVersionUID = -4086031558333008209L;

	private JsonModel jm=new JsonModel();
	private String op;
	private String valcode;
	private String aname;
	private String apwd;
	private CustomerServiceBiz customerSeriveceBiz;
	private HttpServletRequest request=ServletActionContext.getRequest();
	
	@Override
	public String execute() throws Exception {
		if(op!=null){
			if("backlogin".equals(op)){
				loginOp( );
			}else if("backlogout".equals(op)){
				logoutOp( );
			}
		}
		return "success";
	}
	//客服登出操作
	private void logoutOp() {
		HttpSession session=request.getSession();
		haipumi_customerService customerService=(haipumi_customerService) session.getAttribute(CommonData.CUSTOMERSERVICESESSION);
		boolean flag=false;
		if(customerService!=null){
			customerService.setCstatus("0");
			flag=customerSeriveceBiz.logout(customerService);
			session.removeAttribute(CommonData.CUSTOMERSERVICESESSION);
			if(flag){
				jm.setCode(1);//登出成功
			}else{
				jm.setCode(0);//登出失败
			}
		}else{
			jm.setCode(2);//session中数据已经失效
			jm.setMsg("登陆已经失效");
		}
	}

	//客服登陆操作
	private void loginOp( ) {
		//判断验证码的正确性
		HttpSession session=request.getSession();
		if(!session.getAttribute(CommonData.CODESESSION).equals(valcode)){
			jm.setCode(0);
			jm.setMsg("验证码错误");
		}else{
			//设置账号密码
			haipumi_customerService customerService=new haipumi_customerService(aname,apwd);
			
			haipumi_customerService customerService2 =customerSeriveceBiz.login(customerService);
			
			if(customerService2!=null){
				//找到了用户   存到session中，并返回jm
				session.setAttribute(CommonData.CUSTOMERSERVICESESSION, customerService2);
				jm.setCode(1);
				jm.setObj(customerService);
			}else{
				jm.setCode(0);
				jm.setMsg("没有此用户或者用户名密码错误，请确认后重新输入...");
			}
		}
	}

	public void setValcode(String valcode) {
		this.valcode = valcode;
	}

	public String getOp() {
		return op;
	}

	public void setOp(String op) {
		this.op = op;
	}

	public JsonModel getJm() {
		return jm;
	}

	public void setAname(String aname) {
		this.aname = aname;
	}

	public void setApwd(String apwd) {
		this.apwd = apwd;
	}

	@Resource(name = "customerServiceBiz")
	public void setCustomerSeriveceBiz(CustomerServiceBiz customerSeriveceBiz) {
		this.customerSeriveceBiz = customerSeriveceBiz;
	}
}
